package com.ews.onlineexchange.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLEncoder;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import javax.inject.Inject;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import com.ews.onlineexchange.dao.SimpleEntityManagerDao;
import com.ews.onlineexchange.model.Attachment;
import com.ews.onlineexchange.util.AttachmentUtils;
import com.ews.onlineexchange.util.Config;

@ManagedBean
@ViewScoped
public class Attachments {

    @Inject
    private SimpleEntityManagerDao dao;
    @Inject
    Config config;
    public StreamedContent getAttr() throws IOException {
        FacesContext context = FacesContext.getCurrentInstance();

        if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
            // So, we're rendering the view. Return a stub StreamedContent so that it will generate right URL.
            return new DefaultStreamedContent();
        } else {
            // So, browser is requesting the image. Return a real StreamedContent with the image bytes.
            Object id = context.getExternalContext().getRequestParameterMap().get("id");
            Attachment attr = dao.find(Attachment.class, id);
            String saveDir = config.getProperty("com.ews.onlineExchange.saveDir");
            String fullPath = saveDir + attr.getFilepath();
            return new DefaultStreamedContent(new ByteArrayInputStream(AttachmentUtils.getBytes(fullPath)), attr.getContentType(),attr.getFilename());
        }
    }

}
